package com.zbw.common.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.zbw.common.config.AlipayProperties;
import com.zbw.common.service.OrderService;
import com.zbw.common.vo.UserDetails;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author Zbw
 * @Date 27/1
 */
@Controller
@RequestMapping("pay")
@Slf4j
@RequiredArgsConstructor
public class PayContoller extends BaseController{

    private final AlipayProperties alipayProperties;

    private final OrderService orderService;

    @SneakyThrows
    @PostMapping("aliPay")
    public void alipay(Integer payAmount, HttpServletRequest request, HttpServletResponse httpResponse){
        UserDetails userDetails = getUserDetails(request);
        if (userDetails == null){
            httpResponse.sendRedirect("/user/login.html?originUrl=/pay/index.html");
        }else {
            Long outTradeNo = orderService.createPayOrder((byte) 1, payAmount, userDetails.getId());
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGatewayUrl(),
                    alipayProperties.getAppId(), alipayProperties.getMerchantPrivateKey(), "json", alipayProperties.getCharset(),
                    alipayProperties.getPublicKey(), alipayProperties.getSignType());
            String form;
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
            //在公共参数中设置回跳和通知地址
            alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
            //填充业务参数
            alipayRequest.setBizContent("{" +
                    "    \"out_trade_no\":\"" + outTradeNo + "\"," +
                    "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                    "    \"total_amount\":" + payAmount + "," +
                    "    \"subject\":\"知文小说网\"" +
                    "  }");
            //调用SDK生成表单
            AlipayTradePagePayResponse payResponse = alipayClient.pageExecute(alipayRequest);
            form = payResponse.getBody();
            httpResponse.setContentType("text/html;charset=utf-8");
            //直接将完整的表单html输出到页面
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        }


    }


    /**
     * 支付宝支付通知
     */
    @SneakyThrows
    @RequestMapping("aliPay/notify")
    public void aliPayNotify(HttpServletRequest request, HttpServletResponse httpResponse) {

        PrintWriter out = httpResponse.getWriter();

        //获取支付宝POST过来的信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        //验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getPublicKey(),
                alipayProperties.getCharset(), alipayProperties.getSignType());

        if (signVerified) {
            //验证成功
            //商户订单号
            String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);

            //支付宝交易号
            String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);

            //交易状态
            String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);

            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                //支付成功
                orderService.updatePayOrder(Long.parseLong(outTradeNo), tradeNo, 1);
            }

            out.println("success");

        } else {//验证失败
            out.println("fail");

        }

    }


}
